<template>
  <div v-loading="loading">
    <div class="head">
      <div class="app-main-top-box">
        <div class="title">{{ productMode === "edit" ? "编辑资源" : "新增资源" }}</div>
        <div>
          <el-button size="medium" round @click="goBack">返回</el-button>
        </div>
      </div>

      <!-- productType类型 -->
      <div class="product-type-card">
        <el-card
          v-if="
            form.productType == 0 ||
              (productMode === 'add' &&
                !$store.getters.banBtnList.includes(
                  'MCH_BTN_BK_FD_TYPE_CREATE'
                ))
          "
          :shadow="form.productType == 0 ? 'always' : 'never'"
          :class="{ 'app-text-color-primary': form.productType == 0 }"
          @click.native="changeProductType(0)"
        >全日房</el-card>
        <el-card
          v-if="
            form.productType == 1 ||
              (productMode === 'add' &&
                !$store.getters.banBtnList.includes(
                  'MCH_BTN_BK_HR_TYPE_CREATE'
                ))
          "
          :shadow="form.productType == 1 ? 'always' : 'never'"
          :class="{ 'app-text-color-primary': form.productType == 1 }"
          @click.native="changeProductType(1)"
        >钟点房</el-card>
        <el-card
          v-if="
            form.productType == 2 ||
              (productMode === 'add' &&
                !$store.getters.banBtnList.includes(
                  'MCH_BTN_BK_KTV_TYPE_CREATE'
                ))
          "
          :shadow="form.productType == 2 ? 'always' : 'never'"
          :class="{ 'app-text-color-primary': form.productType == 2 }"
          @click.native="changeProductType(2)"
        >KTV</el-card>
      </div>

      <div class="tab">
        <el-tabs v-model="tabName">
          <el-tab-pane label="基础信息" name="0" />
          <el-tab-pane label="资源参数" name="1" />
          <el-tab-pane label="优惠/折扣" name="2" />
          <el-tab-pane label="免接单" name="3" />
          <el-tab-pane label="属性标签" name="4" />
        </el-tabs>
      </div>
    </div>

    <div class="content app-main-content-box">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-suffix="："
        label-width="120px"
        size="small"
      >
        <div v-show="tabName == 0">
          <el-form-item label="资源图片" prop="imageList">
            <div class="img-list">
              <draggable :list="form.imageList" :options="{ filter: '.undrag' }">
                <div v-for="(v, i) in form.imageList" :key="i" class="img-item drag">
                  <img :src="v.url" alt>
                  <div class="handle-icon">
                    <i class="el-icon-zoom-in icon" @click="handlePreview(v)" />
                    <i class="el-icon-delete icon" @click="handleRemove(v, i)" />
                  </div>
                </div>

                <div class="img-item undrag">
                  <el-upload
                    :limit="10"
                    :action="actionUrl"
                    :headers="{ 'X-BUSINESS-TOKEN': $store.state.user.token }"
                    :file-list="form.imageList"
                    :before-upload="handleBefore"
                    :on-success="handleSuccess"
                    :on-exceed="handleExceed"
                    drag
                    multiple
                    :show-file-list="false"
                    list-type="picture-card"
                    class="upload-container"
                  >
                    <i class="el-icon-upload" />
                    <div class="el-upload__text">
                      将文件拖到此处，或
                      <em>点击上传</em>
                    </div>
                  </el-upload>
                  <el-dialog title="图片预览" :visible.sync="dialogImageVisible">
                    <img width="100%" :src="dialogImageUrl" alt>
                  </el-dialog>
                </div>
              </draggable>
            </div>
            <div class="upload-tips">
              <div>1.只能上传jpg/png文件，且不超过1mb</div>
              <div>2.建议尺寸1060*530像素，最多上传10张</div>
              <div>3.可长按图片进行拖拽排序</div>
            </div>
          </el-form-item>
          <el-form-item label="资源名称" prop="name">
            <el-input v-model.trim="form.name" placeholder="请输入资源名称" clearable style="width:500px" />
          </el-form-item>
          <el-form-item label="资源说明" prop="description">
            <el-input
              v-model.trim="form.description"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 5 }"
              maxlength="300"
              placeholder="请输入说明内容"
              style="width:500px"
            />
          </el-form-item>
          <el-form-item label="下单提示" prop="bookingTips">
            <el-input
              v-model.trim="form.bookingTips"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 5 }"
              maxlength="300"
              placeholder="请输入提示内容"
              style="width:500px"
            />
            <el-popover placement="top-start" width="400" trigger="hover">
              <img v-show="form.productType == 0" src="@/assets/preview/p-full-day-room.png" alt>
              <img v-show="form.productType == 1" src="@/assets/preview/p-hour-room.png" alt>
              <img v-show="form.productType == 2" src="@/assets/preview/p-ktv-room.png" alt>
              <i
                slot="reference"
                class="el-icon-warning app-text-color-primary"
                style="font-size:16px"
              />
            </el-popover>
          </el-form-item>
          <el-form-item
            v-if="form.productType == 1 || form.productType == 2"
            label="时长"
            prop="periodDuration"
          >
            <el-input
              v-model.trim="form.periodDuration"
              maxlength="5"
              style="width:200px"
              placeholder="请输入内容"
            >
              <template slot="append">小时</template>
            </el-input>
          </el-form-item>
          <el-form-item label="基础价格" prop="basePrice">
            <el-input v-model="form.basePrice" style="width:200px" placeholder="请输入内容">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item
            v-if="form.productType == 1 || form.productType == 2"
            label="可使用日期"
            prop="customWeekdayLimitRadio"
          >
            <el-radio-group v-model="form.customWeekdayLimitRadio">
              <el-radio v-model="form.customWeekdayLimitRadio" label="0">不限</el-radio>
              <br>
              <el-radio v-model="form.customWeekdayLimitRadio" label="1">指定每周日期</el-radio>
            </el-radio-group>
            <div v-if="form.customWeekdayLimitRadio === '1'" class="nest-card-box">
              <el-card>
                <el-form-item prop="weekdayLimit">
                  <el-checkbox-group v-model="form.weekdayLimit">
                    <el-checkbox-button
                      v-for="(weekItem, weekIndex) in weekOptions"
                      :key="weekIndex"
                      :label="weekItem.value"
                    >{{ weekItem.label }}</el-checkbox-button>
                  </el-checkbox-group>
                </el-form-item>
              </el-card>
            </div>
          </el-form-item>
          <el-form-item
            v-if="form.productType == 1 || form.productType == 2"
            label="可使用时段"
            prop="customPeriodTimeRadio"
          >
            <el-radio-group v-model="form.customPeriodTimeRadio">
              <div>
                <el-radio label="0">不限</el-radio>
              </div>
              <div>
                <el-radio v-model="form.customPeriodTimeRadio" label="1">指定时间段（不跨日）</el-radio>
              </div>
              <div v-if="form.customPeriodTimeRadio === '1'" class="nest-card-box">
                <el-card>
                  <el-form-item prop="customPeriodTime">
                    <el-time-picker
                      v-model="form.customPeriodTime"
                      is-range
                      value-format="HH:mm"
                      format="HH:mm"
                      range-separator="~"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      placeholder="选择时间范围"
                    />
                  </el-form-item>
                </el-card>
              </div>
              <div>
                <el-radio v-model="form.customPeriodTimeRadio" label="2">指定时间段（跨日）</el-radio>
              </div>
            </el-radio-group>
            <div v-if="form.customPeriodTimeRadio === '2'" class="nest-card-box">
              <el-card>
                <el-form-item
                  label="当天"
                  label-width="80px"
                  style="display:inline-block"
                  prop="periodStartTime"
                >
                  <el-time-picker
                    v-model="form.periodStartTime"
                    value-format="HH:mm"
                    format="HH:mm"
                    placeholder="请选择"
                  />
                </el-form-item>
                <el-form-item
                  label="次日"
                  label-width="80px"
                  style="display:inline-block"
                  prop="periodEndTime"
                >
                  <el-time-picker
                    v-model="form.periodEndTime"
                    value-format="HH:mm"
                    format="HH:mm"
                    :picker-options="{ selectableRange: '00:01:00 - 23:59:00' }"
                    placeholder="请选择"
                  />
                </el-form-item>
              </el-card>
            </div>
          </el-form-item>
        </div>

        <!-- 参数 -->
        <div v-show="tabName == 1">
          <el-form-item label="资源参数">
            <div
              v-for="(item, index) in form[
                productAttrListOptions[form.productType]
              ]"
              :key="index"
            >
              <el-form-item
                style="display:inline-block"
                :prop="
                  productAttrListOptions[form.productType] +
                    '.' +
                    index +
                    '.attrName'
                "
                :rules="rules.attrName"
              >
                <el-input
                  v-model.trim="item.attrName"
                  placeholder="请输入参数名"
                  maxlength="10"
                  style="width:150px"
                />
              </el-form-item>
              <el-form-item
                style="display:inline-block"
                :prop="
                  productAttrListOptions[form.productType] +
                    '.' +
                    index +
                    '.attrValue'
                "
              >
                <el-input
                  v-model.trim="item.attrValue"
                  placeholder="请输入参数描述内容，为空顾客端不展示"
                  style="width:300px"
                  maxlength="100"
                />&nbsp;&nbsp;
                <el-button
                  icon="el-icon-delete"
                  type="text"
                  class="app-text-color-danger"
                  @click="delAttr(index)"
                />
              </el-form-item>
            </div>
            <el-form-item>
              <el-button
                type="text"
                icon="el-icon-plus"
                style="display:block"
                @click="addAttr"
              >增加资源参数</el-button>
            </el-form-item>
          </el-form-item>
        </div>

        <div v-show="tabName == 2">
          <el-form-item label="参与优惠" prop="canUseDiscount">
            <el-radio-group v-model="form.canUseDiscount">
              <el-radio :label="1">参与优惠</el-radio>
              <br>
              <el-radio :label="0">不参与任何优惠</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>

        <div v-show="tabName == 3">
          <el-form-item label="自动接单" prop="autoTake">
            <el-radio-group v-model="form.autoTake">
              <el-radio v-model="form.autoTake" :label="0">需要人工确认订单</el-radio>
              <br>
              <el-radio v-model="form.autoTake" :label="1">顾客下单成功后系统自动确认订单</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>

        <div v-show="tabName == 4">
          <el-form-item label="资源标签">
            <div class="transfer-container">
              <div class="left-transfer">
                <div class="transfer-title">
                  <span>已选标签</span>
                  <el-popover placement="top-start" width="300" trigger="hover">
                    <img src="@/assets/preview/p-room-tags.png" alt>
                    <i
                      slot="reference"
                      class="el-icon-warning app-text-color-primary"
                      style="font-size:16px"
                    />
                  </el-popover>
                </div>
                <div class="transfer-filter">
                  <el-input
                    v-model="leftTransferFilterVal"
                    placeholder="请输入搜索内容"
                    prefix-icon="el-icon-search"
                    maxlength="10"
                    clearable
                  />
                </div>
                <ul class="transfer-content">
                  <li
                    v-show="leftTransferFilterVal==''&&form.tagList.length==0"
                    class="transfer-empty"
                  >无数据</li>
                  <li
                    v-show="leftTransferFilterVal!=''&&leftTransferFilterList.length===0"
                    class="transfer-empty"
                  >无匹配数据</li>
                  <li
                    v-for="item in leftTransferFilterVal!=''?leftTransferFilterList:tagList"
                    :key="item.id"
                    class="transfer-item"
                  >
                    <div v-show="form.tagList.includes(item.id)" @click="leftCheckChange(item.id)">
                      <i class="el-icon-close app-text-color-danger" />
                      {{ item.title }}
                    </div>
                  </li>
                </ul>
              </div>
              <div class="right-transfer">
                <div class="transfer-title">候选标签</div>
                <div class="transfer-filter">
                  <el-input
                    v-model="rightTransferFilterVal"
                    placeholder="请输入搜索内容"
                    prefix-icon="el-icon-search"
                    maxlength="10"
                    clearable
                  />
                </div>
                <ul class="transfer-content">
                  <li
                    v-show="rightTransferFilterVal==''&&(tagList.length==0||(tagList.length!==0&&form.tagList.length===tagList.length))"
                    class="transfer-empty"
                  >无数据</li>
                  <li
                    v-show="rightTransferFilterVal!=''&&rightTransferFilterList.length===0"
                    class="transfer-empty"
                  >无匹配数据</li>
                  <li
                    v-for="item in rightTransferFilterVal!==''?rightTransferFilterList:tagList"
                    :key="item.id"
                    class="transfer-item"
                  >
                    <div
                      v-show="!form.tagList.includes(item.id)"
                      @click="rightCheckChange(item.id)"
                    >{{ item.title }}</div>
                  </li>
                </ul>
              </div>
            </div>
          </el-form-item>
        </div>

        <el-form-item>
          <el-button v-show="tabName > 0" round size="small" @click="prevPage">上一页</el-button>
          <el-button type="primary" round size="small" @click="submit">保 存</el-button>
          <el-button v-show="tabName < 4" round size="small" @click="nextPage">下一页</el-button>

          <!-- <el-button round size="small" @click="submit">重 置</el-button> -->
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { imgUploadUrl } from '@/api/upload'
import draggable from 'vuedraggable'
import {
  validateCustomTwoDecimal,
  validateCustomADecimal
} from '@/utils/validate'
import {
  getProductDetail,
  addProduct,
  updateProduct
} from '../../../api/product'
import { getTagList } from '../../../api/tag'
export default {
  components: {
    draggable
  },
  props: {
    productId: {
      require: true
    },
    productMode: {
      type: String,
      require: true
    },
    productType: {
      type: String,
      require: true
    },
    shopId: {
      type: Number,
      require: true
    }
  },
  data() {
    /**
       * 表单校验方法相关
       */
    //  金额
    const validateBasePrice = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入基础价格'))
      } else if (!validateCustomTwoDecimal(value)) {
        callback(new Error('请输入0.01~99999.99范围金额（小数位不超过2位）'))
      } else {
        callback()
      }
    }

    // 时长
    const validatePeriodDuration = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入时长'))
      } else if (!validateCustomADecimal(value)) {
        callback(new Error('请输入正整数，正小数（小数位不超过1位）'))
      } else {
        callback()
      }
    }

    // 选择可使用日期
    const validateWeekdayLimit = (rule, value, callback) => {
      if (value.length === 0) {
        callback(new Error('请选择可使用日期'))
      } else {
        callback()
      }
    }

    // 选择时段
    const validateCustomPeriodTime = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择可使用时段'))
      } else {
        callback()
      }
    }
    return {
      /**
         * 表单校验字段相关
         */
      rules: {
        imageList: [
          { type: 'array', required: true, message: '请至少上传一张图片' }
        ],
        name: [{ required: true, message: '请输入资源名称' }],
        basePrice: [{ required: true, validator: validateBasePrice }],
        periodDuration: [{ required: true, validator: validatePeriodDuration }],
        customWeekdayLimitRadio: [
          { required: true, message: '请选择是否有使用日期限制' }
        ],
        weekdayLimit: [{ required: true, validator: validateWeekdayLimit }],
        customPeriodTimeRadio: [
          { required: true, message: '请选择是否有使用时段限制' }
        ],
        customPeriodTime: [
          { required: true, validator: validateCustomPeriodTime }
        ],
        periodStartTime: [{ required: true, message: '请选择可使用时段' }],
        periodEndTime: [{ required: true, message: '请选择可使用时段' }],
        attrName: [{ required: true, message: '请输入参数名' }],
        autoTake: [{ required: true, message: '请选择是否参与优惠' }],
        canUseDiscount: [{ required: true, message: '请选择是否自动接单' }]
      },
      // 配置
      tabName: '0',
      actionUrl: imgUploadUrl,
      productTypeOptions: {
        0: '全日房',
        1: '钟点房',
        2: 'KTV'
      },
      productAttrListOptions: {
        0: 'customRoomAttrList',
        1: 'customRoomAttrList',
        2: 'customKtvAttrList'
      },
      weekOptions: [
        {
          label: '周一',
          value: '2'
        },
        {
          label: '周二',
          value: '3'
        },
        {
          label: '周三',
          value: '4'
        },
        {
          label: '周四',
          value: '5'
        },
        {
          label: '周五',
          value: '6'
        },
        {
          label: '周六',
          value: '7'
        },
        {
          label: '周日',
          value: '1'
        }
      ],
      //  状态
      loading: false,
      dialogImageVisible: false,
      // 数据
      dialogImageUrl: '',
      tagList: [],
      leftTransferFilterVal: '',
      rightTransferFilterVal: '',
      leftTransferFilterList: [],
      rightTransferFilterList: [],
      form: {
        shopId: '',
        productType: '',
        imageList: [],
        name: '',
        description: '',
        bookingTips: '',
        basePrice: '',
        periodDuration: '',
        customPeriodTimeRadio: '0',
        customPeriodTime: '',
        periodStartTime: '',
        periodEndTime: '',
        customWeekdayLimitRadio: '0',
        weekdayLimit: [],
        customRoomAttrList: [
          { attrName: '早餐', attrValue: '' },
          { attrName: '面积', attrValue: '' },
          { attrName: '楼层', attrValue: '' },
          { attrName: '窗户', attrValue: '' },
          { attrName: '可住', attrValue: '' },
          { attrName: '宽带', attrValue: '' },
          { attrName: '卫浴', attrValue: '' },
          { attrName: '空调', attrValue: '' },
          { attrName: '床型', attrValue: '' }
        ],
        customKtvAttrList: [
          { attrName: '面积', attrValue: '' },
          { attrName: '可容纳人数', attrValue: '' }
        ],
        canUseDiscount: 0,
        autoTake: 0,
        state: 1,
        tagList: []
      }
    }
  },
  watch: {
    leftTransferFilterVal(val) {
      if (val == '') {
        this.leftTransferFilterList = []
        return
      } else {
        const arr = []
        this.tagList.map(v => {
          if (this.form.tagList.includes(v.id) && v.title.indexOf(val) !== -1) {
            arr.push(v)
          }
        })
        this.leftTransferFilterList = arr
      }
    },
    rightTransferFilterVal(val) {
      if (val == '') {
        this.leftTransferFilterList = []
        return
      } else {
        const arr = []
        this.tagList.map(v => {
          if (
            !this.form.tagList.includes(v.id) &&
              v.title.indexOf(val) !== -1
          ) {
            arr.push(v)
          }
        })
        this.rightTransferFilterList = arr
      }
    }
  },
  computed: {
    ...mapGetters(['fileBaseUrl'])
  },
  mounted() {
    this.initData()
  },
  methods: {
    /**
       * 获取数据
       */
    // 获取表单
    initData() {
      if (this.productMode === 'add') {
        const addAuthArr = []
        if (
          !this.$store.getters.banBtnList.includes('MCH_BTN_BK_FD_TYPE_CREATE')
        ) {
          addAuthArr.push('0')
        }
        if (
          !this.$store.getters.banBtnList.includes('MCH_BTN_BK_HR_TYPE_CREATE')
        ) {
          addAuthArr.push('1')
        }
        if (
          !this.$store.getters.banBtnList.includes('MCH_BTN_BK_KTV_TYPE_CREATE')
        ) {
          addAuthArr.push('2')
        }
        this.form.productType = addAuthArr.includes(this.productType)
          ? this.productType
          : addAuthArr[0]
        this.form.shopId = this.shopId
        this.getTag()
      } else {
        this.loading = true
        Promise.all([this.getTag(), this.getDetail()]).then(() => {
          this.loading = false
        })
      }
    },

    // fetch 详情 tab标签
    getTag() {
      return new Promise((resolve, reject) => {
        getTagList()
          .then(res => {
            this.tagList = res.data
          })
          .finally(() => {
            resolve()
          })
      })
    },

    // 获取详情
    getDetail() {
      return new Promise((resolve, reject) => {
        getProductDetail({ productId: this.productId })
          .then(res => {
            this.resetData(res.data)
          })
          .finally(() => {
            resolve()
          })
      })
    },

    // 格式化数据
    resetData(params) {
      switch (params.productType) {
        case 0:
          break
        case 1:
        case 2:
          // 时长
          params.periodDuration = params.periodDuration / 60

          // 时段
          if (!params.weekdayLimit) {
            params.customWeekdayLimitRadio = '0'
            params.weekdayLimit = []
          } else {
            params.customWeekdayLimitRadio = '1'
            params.weekdayLimit = params.weekdayLimit.split(',')
          }

          // 时间
          if (params.periodStartTime === 0 && params.periodEndTime === 0) {
            params.customPeriodTimeRadio = '0'
            params.customPeriodTime = ''
            params.periodStartTime = ''
            params.periodEndTime = ''
          } else if (params.periodEndTime > 1440) {
            params.customPeriodTimeRadio = '2'
            params.periodStartTime =
                Math.floor(params.periodStartTime / 60) +
                ':' +
                (params.periodStartTime % 60)
            const periodEndTime = params.periodEndTime - 1440
            params.periodEndTime =
                Math.floor(periodEndTime / 60) + ':' + (periodEndTime % 60)
            params.customPeriodTime = ''
          } else {
            params.customPeriodTimeRadio = '1'
            params.customPeriodTime = [
              Math.floor(params.periodStartTime / 60) +
                  ':' +
                  (params.periodStartTime % 60),
              Math.floor(params.periodEndTime / 60) +
                  ':' +
                  (params.periodEndTime % 60)
            ]
            params.periodStartTime = ''
            params.periodEndTime = ''
          }
          break
      }
      // 价格
      params.basePrice = params.basePrice / 100
      // 图片
      params.imageList = params.imageList.map((value, index) => {
        return {
          response: { code: 0, data: { path: value } },
          url: this.fileBaseUrl + value
        }
      })
      // tag
      const tagIdsArr = []
      params.tagList = params.tagList.map(v => {
        tagIdsArr.push(v.id)
      })
      params.tagList = tagIdsArr
      params[this.productAttrListOptions[params.productType]] = params.attrList
      if (this.productMode === 'copy') {
        delete params['id']
        delete params['productNo']
      }

      console.log(params)
      this.form = params
      this.$refs.form.clearValidate()
      this.loading = false
    },

    /**
       * 按钮组
       */
    // 保存
    submit() {
      this.$refs.form.validate((valid, object) => {
        if (!valid) {
          const flag = Object.keys(object).some((v, i) => {
            if (
              [
                'imageList',
                'name',
                'basePrice',
                'periodDuration',
                'customPeriodTimeRadio',
                'customPeriodTime',
                'customWeekdayLimitRadio',
                'weekdayLimit'
              ].includes(v)
            ) {
              this.tabName = '0'
              return true
            } else if (
              v.indexOf('customRoomAttrList') !== -1 ||
                v.indexOf('customKtvAttrList') !== -1
            ) {
              this.tabName = '1'
              return true
            } else if (['canUseDiscount'].includes(v)) {
              this.tabName = '2'
              return true
            } else if (['autoTake'].includes(v)) {
              this.tabName = '3'
              return true
            }
          })
        } else {
          const params = Object.assign({}, this.form)
          // 判断类型
          switch (Number(params.productType)) {
            case 0:
              params.periodStartTime = 0
              params.periodEndTime = 0
              params.periodDuration = 0
              params.weekdayLimit = ''
              break
            case 1:
            case 2:
              // 时间
              if (params.customPeriodTimeRadio === '0') {
                params.periodStartTime = 0
                params.periodEndTime = 0
              } else if (params.customPeriodTimeRadio === '1') {
                params.periodStartTime = params.customPeriodTime[0].split(':')
                params.periodEndTime = params.customPeriodTime[1].split(':')
                params.periodStartTime =
                    +params.periodStartTime[0] * 60 + +params.periodStartTime[1]
                params.periodEndTime =
                    +params.periodEndTime[0] * 60 + +params.periodEndTime[1]
              } else if (params.customPeriodTimeRadio === '2') {
                params.periodStartTime = params.periodStartTime.split(':')
                params.periodEndTime = params.periodEndTime.split(':')
                params.periodStartTime =
                    +params.periodStartTime[0] * 60 + +params.periodStartTime[1]
                params.periodEndTime =
                    +params.periodEndTime[0] * 60 +
                    +params.periodEndTime[1] +
                    1440
              }
              // 时段
              if (params.customWeekdayLimitRadio === '0') {
                params.weekdayLimit = ''
              } else {
                params.weekdayLimit = params.weekdayLimit.join(',')
              }
              // 时长
              params.periodDuration = this.$math.mul(
                params.periodDuration,
                60,
                0
              )
              break
          }
          params.attrList =
              params[this.productAttrListOptions[params.productType]]
          params.basePrice = this.$math.mul(params.basePrice, 100, 0)
          delete params.customPeriodTimeRadio
          delete params.customPeriodTime
          delete params.customWeekdayLimitRadio
          // 处理图片
          params.imageList = params.imageList.map(v => {
            if (
              v.response &&
                v.response.code === 0 &&
                v.response.data &&
                v.response.data.path
            ) {
              return v.response.data.path
            }
          })
          // 处理tag
          const tagObjArr = []
          this.tagList.map(v => {
            if (params.tagList.includes(v.id)) {
              tagObjArr.push(v)
            }
          })
          params.tagList = tagObjArr

          // 新增
          this.loading = true
          if (this.productMode === 'add' || this.productMode === 'copy') {
            addProduct(params)
              .then(res => {
                this.$notify({
                  title: '成功',
                  message: '新增成功',
                  type: 'success',
                  duration: 2000,
                  offset: 40
                })
                this.$emit('changeProductMode', {
                  productMode: 'list',
                  refresh: true,
                  productType: params.productType
                })
              })
              .catch(err => {})
              .finally(() => {
                this.loading = false
              })
          } else {
            updateProduct(params)
              .then(res => {
                this.$notify({
                  title: '成功',
                  message: '更新成功',
                  type: 'success',
                  duration: 2000,
                  offset: 40
                })
                this.$emit('changeProductMode', {
                  productMode: 'list',
                  refresh: true,
                  productType: params.productType
                })
              })
              .catch(err => {})
              .finally(() => {
                this.loading = false
              })
          }
        }
      })
    },

    // 更换类型
    changeProductType(type) {
      if (this.productMode !== 'add') return
      this.form.productType = type
      this.$refs.form.clearValidate()
    },

    // 返回
    goBack() {
      this.$emit('changeProductMode', { productMode: 'list' })
    },

    // 增加参数
    addAttr() {
      this.form[this.productAttrListOptions[this.form.productType]].push({
        attrName: '',
        attrValue: ''
      })
    },

    // 删除参数
    delAttr(index) {
      this.form[this.productAttrListOptions[this.form.productType]].splice(
        index,
        1
      )
    },

    // 上传图片
    handleBefore(file) {
      return this.beforeUploadImg(file, this, 0, 0, 1)
    },

    handleSuccess(res, file, fileList) {
      if (res.code === 0) {
        fileList.map
        this.form.imageList = fileList
        this.$refs.form.clearValidate(['imageList'])
      } else {
        this.$message.error(res.msg)
      }
    },

    handleRemove(v, i) {
      this.form.imageList.splice(i, 1)
    },

    handlePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogImageVisible = true
    },

    handleExceed() {
      this.$message.error('最多上传10张')
    },

    // 上一页
    prevPage() {
      this.tabName = String(+this.tabName - 1)
    },

    // 下一页
    nextPage() {
      this.tabName = String(+this.tabName + 1)
      console.log(this.tabName)
    },

    /**
       *  状态组
       */
    // 已选中
    leftCheckChange(id) {
      // this.form.tagList.some((v, i) => {
      //   if (id === v) {
      //     this.form.tagList.splice(i, 1);
      //     return true;
      //   }
      // });
      this.form.tagList.splice(
        this.form.tagList.findIndex(item => item === id),
        1
      )
    },

    // 未选中
    rightCheckChange(id) {
      this.form.tagList.push(id)
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  /*类型卡片 */
  .product-type-card {
    cursor: pointer;
    .el-card {
      display: inline-block;
      font-weight: bold;
    }
  }

  /*  头部 */
  .head {
    padding: 24px 30px 0;
    border-radius: 5px;
    background-color: #fff;
    /* tab */
    .tab ::v-deep {
      .el-tabs__header {
        margin-bottom: 0;
        background-color: #fff;
        border-radius: 0 0 5px 5px;
      }
      .el-tabs__nav-wrap::after {
        background-color: #fff;
      }
      .el-tabs__active-bar {
        height: 4px;
      }
    }
  }

  /* 内容 */
  .content {
    margin-top: 10px;
    .upload-container ::v-deep {
      .el-upload-dragger {
        width: 298px;
        height: 148px;
      }
      .el-upload--picture-card {
        line-height: 1;
        width: 300px;
        height: 150px;
        border: none;
      }
      .el-upload-list__item {
        width: 300px;
        height: 150px;
      }
    }
  }

  /* 穿梭框 */
  .transfer-container {
    display: flex;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    max-height: 100%;
    position: relative;
    .left-transfer,
    .right-transfer {
      width: 200px;
      border: 1px solid #ebeef5;
    }
    .left-transfer {
      margin-right: 50px;
    }
    .transfer-title {
      height: 40px;
      line-height: 40px;
      background: #f5f7fa;
      padding-left: 15px;
      border-bottom: 1px solid #ebeef5;
      color: #000;
    }
    .transfer-filter {
      text-align: center;
      margin: 15px;
    }
    .transfer-content {
      height: 400px;
      padding: 6px 0 6px 10px;
      overflow: auto;
      color: #606266;
      .transfer-item {
        cursor: pointer;
        :hover {
          color: #4d82f3;
        }
      }
    }
    .transfer-empty {
      margin: 0;
      height: 30px;
      line-height: 30px;
      padding-right: 10px;
      color: #909399;
      text-align: center;
    }
    ::v-deep .el-input__inner {
      border-radius: 16px;
    }
  }

  /* 格式化 */
  .el-radio {
    line-height: 32px;
  }

  /* 上传图片列表 */
  .img-list {
    margin: 0;
    display: inline;
    vertical-align: top;
    cursor: pointer;
    .img-item {
      position: relative;
      overflow: hidden;
      background-color: #fff;
      border: 1px solid #c0ccda;
      border-radius: 6px;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      height: 150px;
      width: 300px;
      margin: 0 8px 8px 0;
      display: inline-block;
      &:hover {
        font-size: 20px;
        color: #fff;
        .handle-icon {
          position: absolute;
          top: 0;
          left: 0;
          display: flex;
          align-items: center;
          justify-content: center;
          width: 100%;
          height: 100%;
          background-color: rgba(0, 0, 0, 0.5);
          .icon {
            margin: 10px;
          }
        }
      }
    }
  }
</style>
